package com.yx.elastic.elasticcm.config;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit;

/**
 * Created by chenzp on 18-7-31.
 */
public class ResTData {

    // 业务请求失败
    public static  final int  FAIL= 1;
    //请求异常（系统异常）
    public static  final int ERROR = -1;
    //请求成功
    public static  final int SUCCESS = 0;

    private int code = 0;

    private String msg;

    private int count;

    private JSONArray data;

    public ResTData() {
    }

    public ResTData(int count, JSONArray data) {
        this.count = count;
        this.data = data;
    }


    public ResTData(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ResTData(int code, String msg, JSONArray data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 针对搜索引擎分页处理数据
     * @param query
     */
    public ResTData(SearchResponse query) {
        this.count = (int)query.getHits().getTotalHits();

        SearchHit[] hits = query.getHits().getHits();
        JSONArray jsonArray = new JSONArray();
        for (SearchHit hit : hits) {
            JSONObject o = (JSONObject) JSON.toJSON(hit.getSourceAsMap());
            o.put("id", hit.getId());
            jsonArray.add(o);
        }
        this.data = jsonArray;
    }





    /**
     * 请求成功
     * 写入数据
     * @param data
     */
    public ResTData(JSONArray data) {
        this.data = data;
    }

    /**
     * 业务请求错误构
     * @param msg
     */
    public ResTData(String msg) {
        this.code = 1;
        this.msg = msg;
    }

    public ResTData(int code, String msg, int count, JSONArray data) {
        this.code = code;
        this.msg = msg;
        this.count = count;
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public JSONArray getData() {
        return data;
    }

    public void setData(JSONArray data) {
        this.data = data;
    }
}
